window.onload = () => {
    const VSHADER_SOURCE = `
    attribute vec4 a_Position;
    void main(){
      gl_Position = a_Position;
    }`;

    const FSHADER_SOURCE = `
    precision mediump float;
    uniform vec4 u_FragColor;
    void main(){
      gl_FragColor = u_FragColor;
    }`;
    const canvas = document.getElementById('webgl');
    const gl = getWebGLContext(canvas);
    if (!gl) {
        console.log('Fail');
        return;
    }
    if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
        console.log('Failed');
        return;
    }

    let a_Position = gl.getAttribLocation(gl.program, 'a_Position');
    let u_FragColor = gl.getUniformLocation(gl.program, 'u_FragColor');

    if (a_Position < 0 || !u_FragColor) {
        return;
    }
    let positonAndColor = [];
    canvas.addEventListener('click', e => {
        let [x, y] = [e.clientX, e.clientY];
        let rect = e.target.getBoundingClientRect();
        x = (x - rect.left) / (rect.width / 2) - 1;
        y = 1 - (y - rect.top) / (rect.height / 2);
        positonAndColor.push([
            [x, y, x - 0.1, y - 0.1, x + 0.1, y - 0.1],
            [Math.random(), Math.random(), Math.random(), Math.random()]
        ]);
        let vertexBuffer = gl.createBuffer();
        if (!vertexBuffer) return;
        gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
        gl.clear(gl.COLOR_BUFFER_BIT);
        for (let val of positonAndColor) {
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(val[0]), gl.STATIC_DRAW);
            gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
            gl.enableVertexAttribArray(a_Position);

            gl.uniform4f(u_FragColor, ...val[1]);
            gl.drawArrays(gl.LINE_LOOP, 0, 3);
        }
    });
    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    gl.clear(gl.COLOR_BUFFER_BIT);
};